/**     
 * @Title: NettyEmbeddedServletInitializer.java   
 * @Package me.springboot.netty.servlet   
 * @Description: TODO
 * @author weiwei 
 * @date 2017年8月25日 下午2:33:49   
 * @version V1.0     
 */
package me.springboot.netty.servlet;

import static com.google.common.base.Preconditions.checkNotNull;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.util.concurrent.EventExecutorGroup;
import me.springboot.netty.adapter.ServletContentHandler;
import me.springboot.netty.context.NettyEmbeddedContext;
import me.springboot.netty.handler.RequestDispatcherHandler;

/**
 * @ClassName: NettyEmbeddedServletInitializer
 * @Description: TODO
 * @author weiwei
 * @date 2017年8月25日 下午2:33:49
 * 
 */
public class NettyEmbeddedServletInitializer extends ChannelInitializer<SocketChannel> {

	private final EventExecutorGroup servletExecutor;

	private final RequestDispatcherHandler requestDispatcherHandler;

	private final NettyEmbeddedContext servletContext;

	public NettyEmbeddedServletInitializer(EventExecutorGroup servletExecutor, NettyEmbeddedContext servletContext) {
		this.servletContext = servletContext;
		this.servletExecutor = checkNotNull(servletExecutor);
		requestDispatcherHandler = new RequestDispatcherHandler(servletContext);
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		p.addLast("codec", new HttpServerCodec(4096, 8192, 8192, false));
		p.addLast("servletInput", new ServletContentHandler(servletContext));
		p.addLast(servletExecutor, "filterChain", requestDispatcherHandler);
	}
}
